Template.taskEdit.onCreated(function() {
  Session.set('taskEditErrors', {});
});

Template.taskEdit.helpers({
  errorMessage: function(field) {
    return Session.get('taskEditErrors')[field];
  },
  errorClass: function (field) {
    return !!Session.get('taskEditErrors')[field] ? 'has-error' : '';
  }
});

Template.taskEdit.events({
  'submit form': function(e) {
    e.preventDefault();
    
    var currentTaskId = this._id;
    
    var taskProperties = {
      text: $(e.target).find('[name=text]').val()
    }
    
    var errors = validateTask(taskProperties);
    if (errors.text)
      return Session.set('taskEditErrors', errors);
    
    //Tasks.update(currentTaskId, {$set: taskProperties}, function(error) {
    Meteor.call('updateTask', currentTaskId, taskProperties, function(error, result) {
      if (error) {
        // display the error to the user
        throwError(error.reason || error.error || error.message);
      } else {
        Router.go('taskPage', {_id: currentTaskId});
      }
    });
  },
  
  'click .delete': function(e) {
    e.preventDefault();
    
    if (confirm("Delete this task?")) {
      var currentTaskId = this._id;
      //Tasks.remove(currentTaskId);
      Meteor.call("deleteTask", currentTaskId, function(error, result) {
        if (error) {
          // display the error to the user
          throwError(error.reason || error.error || error.message);
        } else {
          Router.go('tasksList');
        }
      });
    }
  }
});
